package com.coolapk.controller;

import com.coolapk.entity.User;
import com.coolapk.result.ResponseResult;
import com.coolapk.service.UserService;
import com.coolapk.uitls.VerificationCode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.coolapk.uitls.Upload.fileUpload;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    private HttpSession session;
    @Resource
    private HttpServletRequest request;
    @Resource
    HttpServletResponse response;

    @PostMapping("/login")
    public ResponseResult Login(@RequestBody User user) {
        List<User> users = userService.login(user);
        if (users.size() < 1) {
            return ResponseResult.failure(-1,"账号或密码错误");
        } else {
            if (users.get(0).getStatus() == 0) {
                return ResponseResult.failure(0,"账号状态不可用");
            } else {
                String token = UUID.randomUUID().toString();
//                System.out.println(token);
                session.setAttribute("token", token);
//                System.out.println(session.getId());
                //不返回密码给前端
                users.get(0).setPassword(null);
                //计算动态数,粉丝数,关注数 set进实体,一并返回
                User u = userService.countNum(users.get(0));
                return ResponseResult.success(1, "登录成功", u, token);
            }
        }
    }

    @GetMapping("/getRegisterCode")
    public void RegisterCode() throws IOException {
        VerificationCode verificationCode = new VerificationCode();
        //获取验证码图片
        BufferedImage image = verificationCode.getImage();
        //获取验证码内容
        String text = verificationCode.getText();
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
        randomCode.append(text);
        // 将验证码保存到Session中。
        HttpSession session = request.getSession();
        session.setAttribute("registerCode", randomCode.toString());
        //System.out.println("session-registerCode==>"+randomCode.toString());
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "jpeg", sos);
        sos.flush();
        sos.close();
    }

    @PostMapping("/register")
    public ResponseResult Register(@RequestBody User user){
        Object sessionCode = session.getAttribute("registerCode");
        String Code = user.getCode();
        //判断该邮箱是否被注册过
        List<User> u = userService.checkUser(user.getEmail());
        if(u.size() > 0){
            return ResponseResult.failure(0,"该邮箱已注册,请前往登录");
        }else {
            //判断验证码是否正确(不区分大小写)
            if (String.valueOf(sessionCode).equalsIgnoreCase(Code)) {
                Integer res = userService.register(user);
                if (res > 0) {
                    return ResponseResult.success(1, "注册成功,请登录");
                } else {
                    return ResponseResult.failure(-1, "注册失败");
                }
            } else {
                return ResponseResult.failure(0, "验证码错误");
            }
        }
    }

    @PutMapping("/updateUserInfo")
    public ResponseResult updateUserInfo(User user){
        if (user.getHeadFile() != null){
            String URL = fileUpload(user.getHeadFile());
            user.setHeadImg(URL);
        }else if (user.getBgcFile() != null){
            String URL = fileUpload(user.getBgcFile());
            user.setBackgroundImg(URL);
        }
        int res = userService.updateUserInfo(user);
        if (res > 0){
            return ResponseResult.success(1,"修改成功");
        }else {
            return ResponseResult.failure(-1,"修改失败");
        }
    }

    @GetMapping("/getNewUserInfo/{id}")
    public ResponseResult getNewUserInfo(@PathVariable Integer id){
//        System.out.println(id);
        User user =userService.getNewUserInfo(id);
        //不返回密码给前端
        user.setPassword(null);
        //计算动态数,粉丝数,关注数 set进实体,一并返回
        user = userService.countNum(user);
//        System.out.println(user);
        if (user!=null){
            return ResponseResult.success(1,"获取成功",user);
        }else
        return ResponseResult.failure(-1,"获取失败");
    }
}
